<?php

class CaptchaController extends Zend_Controller_Action
{
    public function init()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
    }

    public function generateAction()
    {
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $security_code =
            substr(sha1(rand(0, 999)), 15, 5);
        $_SESSION['captcha_code'] = $security_code;
        $font = Zend_registry::get('paths')->library . '/Fonts/FreeSans.ttf';
        $width =
            $request->getParam('width') ?
            $request->getParam('width') : 150;
        $height =
            $request->getParam('height') ?
            $request->getParam('height') : 50;
        $fontSize = ceil($width / $height) * 10;

        // Create the image resource
        $image = imagecreate($width, $height);

        // We are making three colors, white, black and gray
        $white = imagecolorallocate($image, 255, 255, 255);
        $black = imagecolorallocate($image, 0, 0, 0);
        $grey = imagecolorallocate($image, 204, 204, 204);

        // Make the background black
        imagefill($image, 0, 0, $black);

        // Add randomly generated string in white to the image:
        $tb = imagettfbbox($fontSize, 0, $font, $security_code);

        // Get x and y to align the text vertically and horizontally
        $x = ceil(($width - $tb[2]) / 2);
        $y = ceil(($height - $tb[5]) / 2);

        // image
        // size
        // angle
        // x, lower left corner of font
        // y, baseline of font
        // color
        // fontfile
        // text
        imagettftext
        (
            $image,
            $fontSize,
            0,
            $x,
            $y,
            $white,
            $font,
            $security_code
        );

        // Throw in some lines to make it a little bit harder for any bots to break
        imagerectangle($image, 0, 0, $width - 1, $height - 1, $grey);
        imageline($image, 0, $height / 2, $width, $height / 2, $grey);
        imageline($image, $width / 2, 0, $width / 2, $height, $grey);

        // Tell the browser what kind of file is come in
        header('Content-Type: image/jpeg');

        // Output the newly created image in jpeg format
        imagepng($image);
        imagedestroy($image);
    }
}
